package com.zhanghu.backendZray.utils.jwt;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTPayload;
import cn.hutool.jwt.JWTUtil;
import com.alibaba.fastjson.JSON;
import com.zhanghu.backendZray.constants.CommonConstant;
import com.zhanghu.backendZray.pojo.dto.UserTokenInfo;

import java.util.HashMap;
import java.util.Map;

/**
 * @author ZhangDong
 * @date 2023/8/18 14:45
 */
public class JwtUtil {

    public static String createToken(UserTokenInfo userTokenInfo) {
        DateTime now = DateTime.now();
        DateTime newTime = now.offsetNew(DateField.MINUTE, CommonConstant.TOKEN_EXPIRE_MINUTES);
        Map<String, Object> payload = new HashMap<>();
        payload.put("user", JSON.toJSONString(userTokenInfo));
        //签发时间
        payload.put(JWTPayload.ISSUED_AT, now);
        //过期时间
        payload.put(JWTPayload.EXPIRES_AT, newTime);
        //生效时间
        payload.put(JWTPayload.NOT_BEFORE, now);
        String token = JWTUtil.createToken(payload, CommonConstant.JWT_KEY.getBytes());
        return token;
    }

    public static boolean verifyTokenExpireTime(String token) {
        JWT jwt = JWTUtil.parseToken(token);
        boolean verify = jwt.setKey(CommonConstant.JWT_KEY.getBytes()).verify();
        boolean verifyTime = jwt.validate(0);
        if (!verify || !verifyTime) {
            return false;
        }
        return true;
    }

    public static UserTokenInfo getUserFromToken(String token) {
        JWT jwt = JWTUtil.parseToken(token);
        boolean verify = jwt.setKey(CommonConstant.JWT_KEY.getBytes()).verify();
        boolean verifyTime = jwt.validate(0);
        if (!verify || !verifyTime) {
            return null;
        }
        String userInfo = String.valueOf(jwt.getPayload("user"));
        UserTokenInfo userTokenInfo = JSON.parseObject(userInfo, UserTokenInfo.class);
        return userTokenInfo;
    }

    public static void main(String[] args) {
//        String token = createToken(new UserTokenInfo(1, "zhangsan","", null));
//        System.err.println("token:"+token);

        String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJuYmYiOjE3MjQyMjU0NjEsImV4cCI6MTcyNDgzMDI2MSwidXNlciI6IntcImlkXCI6MyxcIm5hbWVcIjpcIuW8oOWGrFwiLFwicGhvbmVcIjpcIjE4OTYyNjE0NjM1XCIsXCJ3eEF2YXRhclwiOlwiaHR0cHM6Ly90aGlyZHd4LnFsb2dvLmNuL21tb3Blbi92aV8zMi9IYlFlYWVqbzRleG9OQnpOU3Ntd2xueDgwYW1iZjBVU2lhMXM5OHR4VGRnbXVTcnVQYUN5MnRaRHNpY3NZR1V3WmpEZWdOWkxrUENKUzlDdFFYblZyTjdRLzEzMlwifSIsImlhdCI6MTcyNDIyNTQ2MX0.gwb8n5ZvbAR-t67xE3uR3d-eX2kQ-I4gC5Y0afUjzRo";
        UserTokenInfo userFromToken = getUserFromToken(token);
        System.err.println(JSON.toJSONString(userFromToken));


    }
}
